package com.dy.springbootstudy.second_chapter_web.controller_book_code;

import com.dy.springbootstudy.second_chapter_web.entity.BookOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import javax.validation.Valid;

@Slf4j
@Controller
@RequestMapping("/book/orders")
//这里是可以把创建的 order 对象存储在session中
public class OrderController {

    @GetMapping("/current")
    public String orderForm(Model model) {

        //最好提交的 bookOrder 与 BookOrder 类 是一致的这样可以免去许多麻烦
        model.addAttribute("bookOrder", new BookOrder());
        return "book/orderForm";
    }

 /*   @PostMapping
    public String processOrder(BookOrder order) {
        log.info("Order submitted: " + order);
        return "redirect:/book";
    }*/

    @PostMapping
    public String processOrder(@Valid BookOrder order, Errors errors, Model model) {
        log.info("Order submitted: " + order);
        if (errors.hasErrors()) {
            //事实证明。书本上面的有问题，不过还是可以用其他的方法来进行一个返回的操作
            //加上这个注解 @SessionAttributes("order")，则可以重定向的时候清空数据
            //目前这个错误提示并不能像 书本上面的进行一个显示

            //log.error("hasErrors -> " + errors.getAllErrors());
            //BookOrder bookOrder = new BookOrder();
            //bookOrder.setZip(errors.getAllErrors().get(0).getDefaultMessage());
            //model.addAttribute("order", errors);
            return "book/orderForm";
        }
        return "redirect:/book";
    }

}
